package com.chenxiao.httputils.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * @Author: CX
 * @Date: Created in  2023/12/10 22:20
 * @version: v1.0
 * @Description: TODO
 **/
public class HttpURLConnectionUtils {
    private static HttpURLConnection con;
    /* valid HTTP methods */
    private static final String[] methods = {
            "GET", "POST", "HEAD", "OPTIONS", "PUT", "DELETE", "TRACE"
    };

    public static void doGet(String urls){
        try {
            URL url = new URL(urls);
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;
            StringBuffer content = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                content.append(inputLine);
            }
            in.close();
            con.disconnect();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static String doPost(String url, Map<String, Object> params){
        HttpURLConnection httpConn = null;
        BufferedInputStream bis = null;
        DataOutputStream dos = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            URL urlObj = new URL(url);
            httpConn = (HttpURLConnection) urlObj.openConnection();
            httpConn.setDoInput(true);
            // 允许传入body参数
            httpConn.setDoOutput(true);
            httpConn.setRequestMethod("POST");
            // POST不支持缓存
            httpConn.setUseCaches(false);
            httpConn.setRequestProperty("Connection", "Keep-Alive");
            httpConn.setRequestProperty("Accept", "*/*");
            httpConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            httpConn.setRequestProperty("Cache-Control", "no-cache");
            httpConn.setRequestProperty("Charset", "utf-8");
            // 这个比较重要，按照上面分析的拼装出Content-Type头的内容 https://blog.csdn.net/weiguang102/article/details/119645861
            httpConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConn.connect();

            dos = new DataOutputStream(httpConn.getOutputStream());
            if (params != null && !params.isEmpty()) {
                StringBuilder stringBuilder = new StringBuilder();
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    String key = entry.getKey();
                    Object value = params.get(key);
                    if(stringBuilder.length() == 0) {
                        stringBuilder.append(key).append("=").append(value == null ? "" : value.toString());
                    } else {
                        stringBuilder.append("&").append(key).append("=").append(value == null ? "" : value.toString());
                    }
                }
                // 这里要个换行
                dos.write(stringBuilder.toString().getBytes(StandardCharsets.UTF_8));
                dos.flush();
                dos.close();
            }
            byte[] buffer = new byte[8 * 1024];
            int c = 0;
            if (httpConn.getResponseCode() == 200) {
                bis = new BufferedInputStream(httpConn.getInputStream());
                while ((c = bis.read(buffer)) != -1) {
                    baos.write(buffer, 0, c);
                    baos.flush();
                }
            }
            // 将输入流转成字节数组，返回给客户端。
            return baos.toString("utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (dos != null)
                    dos.close();
                if (bis != null)
                    bis.close();
                baos.close();
                if(httpConn != null) {
                    httpConn.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return null;
    }

}
